﻿using DevExpress.Blazor.Internal;
using DevExpress.ExpressApp;
using DevExpress.ExpressApp.Blazor;
using DevExpress.ExpressApp.Blazor.Editors;
using DevExpress.ExpressApp.Blazor.Services;
using DevExpress.ExpressApp.Model;
using DevExpress.ExpressApp.SystemModule;
using DevExpress.XtraPrinting;
using Microsoft.Extensions.DependencyInjection;
using System.Reflection;

namespace EasyXaf.TreeListEditors.Blazor;

public class TreeListEditor : DxGridListEditor, IExportable
{
    private readonly FieldInfo _gridAdapterField = typeof(DxGridListEditor).GetField("gridAdapter", BindingFlags.Instance | BindingFlags.NonPublic);
    private readonly PropertyInfo _objectSpaceProperty = typeof(DxGridListEditor).GetProperty("ObjectSpace", BindingFlags.Instance | BindingFlags.NonPublic);

    private TreeListAdapter TreeListAdapter
    {
        get => (TreeListAdapter)_gridAdapterField.GetValue(this);
        set => _gridAdapterField.SetValue(this, value);
    }

    private IObjectSpace ObjectSpace => (IObjectSpace)_objectSpaceProperty.GetValue(this);

    private IImageUrlService ImageUrlService { get; set; }

    List<ExportTarget> IExportable.SupportedExportFormats => [];

    public TreeListEditor(IModelListView model)
        : base(model)
    {
        CustomizeCellDisplayTemplate += TreeListEditor_CustomizeCellDisplayTemplate;
    }

    private void TreeListEditor_CustomizeCellDisplayTemplate(object sender, CustomizeCellDisplayTemplateArgs e)
    {
        if (e.ColumnInfo.ModelMember.ModelClass.DefaultProperty == e.ColumnInfo.PropertyName)
        {
            if (e.DataItem is ITreeObjectImage treeObject && !string.IsNullOrWhiteSpace(treeObject.Image))
            {
                var image = DxImage.IconCssOrImage(null, ImageUrlService.GetImageUrl(treeObject.Image), null);
                e.Content = builder =>
                {
                    builder.OpenElement(0, "div");
                    builder.AddAttribute(1, "class", "d-flex align-items-center");
                    builder.AddContent(2, image);
                    builder.OpenElement(3, "span");
                    builder.AddAttribute(4, "class", "ps-1");
                    builder.AddContent(5, e.Context.DisplayText);
                    builder.CloseComponent();
                    builder.CloseElement();
                };
            }
        }
    }

    protected override object CreateControlsCore()
    {
        ImageUrlService = ObjectSpace.ServiceProvider.GetService<IImageUrlService>();

        var treeListModel = new TreeListModel
        {
            KeyFieldName = "Id",
            ParentKeyFieldName = "ParentId",
        };

        TreeListAdapter = new TreeListAdapter(treeListModel);
        if (!BlazorApplication.UseComponentModel)
        {
            return TreeListAdapter;
        }

        return treeListModel;
    }
}
